<template>
	<el-form size="large" class="login-content-form">
		<el-form-item prop="tenantName" v-if="tenantEnable">
			<el-input v-model="loginForm.tenantName" type="text" auto-complete="off" placeholder="租户">
				<el-icon class="tree"></el-icon>
			</el-input>
		</el-form-item>
		<el-form-item class="login-animation1">
			<el-input type="text" placeholder="请输入用户名 " v-model="loginForm.userName" clearable autocomplete="off">
				<template #prefix>
					<el-icon class="el-input__icon"><ele-User /></el-icon>
				</template>
			</el-input>
		</el-form-item>
		<el-form-item class="login-animation2">
			<el-input :type="isShowPassword ? 'text' : 'password'" placeholder="请输入密码" v-model="loginForm.password" autocomplete="off">
				<template #prefix>
					<el-icon class="el-input__icon"><ele-Unlock /></el-icon>
				</template>
				<template #suffix>
					<i
						class="iconfont el-input__icon login-content-password"
						:class="isShowPassword ? 'icon-yincangmima' : 'icon-xianshimima'"
						@click="isShowPassword = !isShowPassword"
					>
					</i>
				</template>
			</el-input>
		</el-form-item>
		<el-form-item class="login-animation3">
			<el-col :span="15">
				<el-input type="text" maxlength="5" placeholder="请输入验证码" v-model="loginForm.code" clearable autocomplete="off" @keyup.enter="onSignIn">
					<template #prefix>
						<el-icon class="el-input__icon"><ele-Position /></el-icon>
					</template>
				</el-input>
			</el-col>
			<div class="login-code">
				<img :src="codeImg" @click="getCode" class="login-code-img" />
			</div>
		</el-form-item>
		<el-form-item class="login-animation4">
			<el-button type="primary" class="login-content-submit" round @click="onSignIn" :loading="loading.signIn" @keyup.enter="onSignIn">
				<span>登 录</span>
			</el-button>
		</el-form-item>
	</el-form>
</template>

<script lang="ts">
import { toRefs, reactive, onMounted, defineComponent, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { initBackEndControlRoutes } from '/@/router/backEnd';
import { useStore } from '/@/store/index';
import { Session } from '/@/utils/storage';
import { formatAxis } from '/@/utils/formatTime';
import { useLoginApi } from '/@/api/login';
import { getTenantIdByName } from '/@/api/system/tenant';
import { getToken, setToken } from '/@/utils/auth';

export default defineComponent({
	name: 'loginAccount',
	setup() {
		const loginApi = useLoginApi();
		const tenantEnable = true;
		const store = useStore();
		const route = useRoute();
		const router = useRouter();
		const state = reactive({
			codeImg: '',
			isShowPassword: false,
			token: getToken(),
			loginForm: {
				tenantName: '芋道源码',
				userName: 'admin',
				password: 'admin123',
				code: '',
				uuid: '',
			},
			loading: {
				signIn: false,
			},
		});
		// 时间获取
		const currentTime = computed(() => {
			return formatAxis(new Date());
		});
		// 获取验证码
		function getCode() {
			loginApi.getCodeImg().then((response) => {
				const res = response.data;
				state.codeImg = 'data:image/gif;base64,' + res.img;
				state.loginForm.uuid = res.uuid;
			});
		}
		// 获取租户
		function getTenantId() {
			getTenantIdByName(state.loginForm.tenantName).then((res) => {
				const tenantId = res.data;
				if (tenantId && tenantId >= 0) {
					// 设置租户
					Session.set('tenantId', tenantId);
				} else {
					ElMessage.error('租户不存在');
				}
			});
		}
		// 登录
		const onSignIn = async () => {
			state.loading.signIn = true;
			if (state.token) {
				signInSuccess();
			}else{
				const loginData = {
					username: state.loginForm.userName.trim(),
					password: state.loginForm.password,
					code: state.loginForm.code,
					uuid: state.loginForm.uuid,
				};
				// 登录请求
				await loginApi
					.login(loginData)
					.then((response) => {
						setToken(response.data.token);
					})
					.catch(() => {
						state.loading.signIn = false;
						window.location.href = '/'; // 去登录页
					});
			}
			// 用户信息
			const userInfos = {
				token: getToken(),
				id: '', // 用户编号
				nickName: '',
				avatar: '',
				time: new Date().getTime(),
				roles: [],
				authBtnList: [],
			};
			await loginApi.getInfo().then((response) => {
				userInfos.id = response.data.id;
				userInfos.nickName = response.data.user.nickName;
				userInfos.avatar = response.data.user.avatar;
				userInfos.roles = response.data.roles;
				userInfos.authBtnList = response.data.permissions;
			});
			// 存储用户信息到浏览器缓存
			Session.set('userInfo', userInfos);
			// 1、请注意执行顺序(存储用户信息到vuex)
			store.dispatch('userInfos/setUserInfos', userInfos);
			// 添加完动态路由，再进行 router 跳转，否则可能报错 No match found for location with path "/"
			await initBackEndControlRoutes();
			// 执行完 initBackEndControlRoutes，再执行 signInSuccess
			signInSuccess();
		};
		// 登录成功后的跳转
		const signInSuccess = () => {
			// 初始化登录成功时间问候语
			let currentTimeInfo = currentTime.value;
			// 登录成功，跳到转首页
			// 添加完动态路由，再进行 router 跳转，否则可能报错 No match found for location with path "/"
			// 如果是复制粘贴的路径，非首页/登录页，那么登录成功后重定向到对应的路径中
			if (route.query?.redirect) {
				router.push({
					path: <string>route.query?.redirect,
					query: Object.keys(<string>route.query?.params).length > 0 ? JSON.parse(<string>route.query?.params) : '',
				});
			} else {
				if (route.query?.redirect) {
					router.push({
						path: <string>route.query?.redirect,
						query: Object.keys(<string>route.query?.params).length > 0 ? JSON.parse(<string>route.query?.params) : '',
					});
				} else {
					router.push('/home');
				}
			}
			// 登录成功提示
			// 关闭 loading
			state.loading.signIn = true;
			const signInText = '欢迎回来！';
			ElMessage.success(`${currentTimeInfo}，${signInText}`);
		};
		// 页面加载时
		onMounted(() => {
			getCode();
			getTenantId();
		});
		return {
			onSignIn,
			getCode,
			tenantEnable,
			...toRefs(state),
		};
	},
});
</script>

<style scoped lang="scss">
.login-content-form {
	margin-top: 20px;
	@for $i from 1 through 4 {
		.login-animation#{$i} {
			opacity: 0;
			animation-name: error-num;
			animation-duration: 0.5s;
			animation-fill-mode: forwards;
			animation-delay: calc($i/10) + s;
		}
	}
	.login-content-password {
		display: inline-block;
		width: 20px;
		cursor: pointer;
		&:hover {
			color: #909399;
		}
	}
	.login-content-code {
		width: 100%;
		padding: 0;
		font-weight: bold;
		letter-spacing: 5px;
	}
	.login-code {
		width: 33%;
		height: 48px;
		float: right;
		img {
			cursor: pointer;
			vertical-align: middle;
			overflow: hidden;
			width: 100%;
		}
	}
	.login-content-submit {
		width: 100%;
		letter-spacing: 2px;
		font-weight: 300;
		margin-top: 15px;
	}
}
</style>
